package com.tianji.remark.task;

import cn.hutool.core.collection.CollUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.StringUtils;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class LikedTimesCheckTask {

    private static final List<String> BIZ_TYPES = List.of("QA", "NOTE");
    private static final int MAX_BIZ_SIZE = 30;

    private final ILikedRecordService recordService;

    private final StringRedisTemplate redisTemplate;

    private final RabbitMqHelper mqHelper;


    @Scheduled(fixedDelay = 20000)
    public void checkLikedTimes() {
        String key = RedisConstants.LIKE_COUNT_KEY_PREFIX;
        for (String bizType : BIZ_TYPES) {
            key += bizType;
            Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(key, MAX_BIZ_SIZE);
            if (CollUtil.isEmpty(typedTuples)) {
                continue;
            }
            ArrayList<LikedTimesDTO> likedTimesDTOS = new ArrayList<>();
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String bizId = typedTuple.getValue();
                Double score = typedTuple.getScore();
                if (bizId == null || score == null) {
                    continue;
                }
                likedTimesDTOS.add(new LikedTimesDTO(Long.valueOf(bizId), score.intValue()));
            }
            if (CollUtil.isNotEmpty(likedTimesDTOS)) {
                //发送消息
                String exchangs = MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
                String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
                mqHelper.send(exchangs, routingKey, likedTimesDTOS);
            }
        }
    }
}